﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using YJTShiftManagement.Events;
using YJTShiftManagement.Models;
using YJTShiftManagement.Service;

namespace YJTShiftManagement
{
    public partial class ShiftManagementPage : UIPage
    {
        private float X, Y;
        private Dictionary<string, string> keyValues = new Dictionary<string, string>();
        private void setTag(Control cons) { foreach (Control con in cons.Controls) { con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size; if (con.Controls.Count > 0) setTag(con); } }
        private void setControls(float newx, float newy, Control cons) { foreach (Control con in cons.Controls) { string[] mytag = con.Tag.ToString().Split(new char[] { ':' }); float a = Convert.ToSingle(mytag[0]) * newx; con.Width = (int)a; a = Convert.ToSingle(mytag[1]) * newy; con.Height = (int)(a); a = Convert.ToSingle(mytag[2]) * newx; con.Left = (int)(a); a = Convert.ToSingle(mytag[3]) * newy; con.Top = (int)(a); Single currentSize = Convert.ToSingle(mytag[4]) * newy; con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); if (con.Controls.Count > 0) { setControls(newx, newy, con); } } }
        private void Form1_Resize(object sender, EventArgs e)

        {
            float newx = (this.Width) / X;
            float newy = this.Height / Y; setControls(newx, newy, this);
            this.Text = this.Width.ToString() + " " + this.Height.ToString();
        }
        private void Form1_Load(object sender, EventArgs e) { this.Resize += new EventHandler(Form1_Resize); X = this.Width; Y = this.Height; y = this.statusStrip1.Height; setTag(this); }

        public ShiftManagementPage()
        {
            InitializeComponent();
            BeginDate.Value = DateTime.Today;
            EndDate.Value = BeginDate.Value.AddMonths(1);

            uiPagination1.ActivePage = 1;
            uiPagination1.PageSize = 21;
            dataGridView1.CellClick += DataGridView1_CellClick;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            TypecomboBox.Items.Add("");
            TypecomboBox.Items.Add("图文");
            TypecomboBox.Items.Add("视频");
            TypecomboBox.Items.Add("远程问诊");
        }
        private void Init()
        {

            InitHeaderData();
            InitDataGrid();
        }

        // 事件处理方法
        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0 && e.ColumnIndex == 0)
                {
                    DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                    DataGridViewCell cell = row.Cells[e.ColumnIndex];
                    string doc_id = null;
                    if (row.Tag is Dictionary<string, object> dataDict)
                    {
                        // 示例1：直接通过键名获取值
                        if (dataDict.TryGetValue("doc_id", out object docId))
                        {
                            doc_id = docId?.ToString(); // 转换为实际类型

                        }
                        EventManager.Instance.RaiseStringEvent(doc_id);
                    }
                    return;
                }
                if (e.RowIndex >= 0 && e.ColumnIndex >= 1)
                {
                    DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                    DataGridViewCell cell = row.Cells[e.ColumnIndex];
                    string doc_id = null;
                    string date = null;
                    if (row.Tag is Dictionary<string, object> dataDict)
                    {
                        // 示例1：直接通过键名获取值
                        if (dataDict.TryGetValue("doc_id", out object docId))
                        {
                            doc_id = docId?.ToString(); // 转换为实际类型


                        }
                        string columnPropertyName = dataGridView1.Columns[e.ColumnIndex].Name;
                        if (dataDict.TryGetValue(columnPropertyName, out object date1))
                        {
                            date = (date1 as kinds)?.date;
                        }

                    }
                    new RecordDetails(doc_id, date).ShowDialog();
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorDialog(ex.Message);
                return;
            }
        }
        private void InitHeaderData()
        {
            string BeginDateStr = "";
            string EndDateStr = "";
            if (DateTime.TryParse(BeginDate.Text, out DateTime beginDate))
            {
                BeginDateStr = beginDate.ToString("yyyy-MM-dd");
            }
            if (DateTime.TryParse(EndDate.Text, out DateTime endDate))
            {
                EndDateStr = endDate.ToString("yyyy-MM-dd");
            }
            var Request = new { end = EndDateStr, start = BeginDateStr, type = "doc" };

            var result = BaseService.HttpService("api_back/api_scheduling/init_sch_dynamic_table_title", Request);

            if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
            {

            }
            else
            {
                this.ShowErrorDialog(result.msg);
                if (result.msg.Contains("认证失败")) { EventManager.Instance.RaiseStringEvent("登录界面"); }
                return;
            }
            dataGridView1.Columns.Clear();

            // 3. 解析JSON数据
            var dateItems = JArray.Parse(result.data.ToString());

            // 4. 清空现有列（保留非日期列）
            var columnsToRemove = dataGridView1.Columns.Cast<DataGridViewColumn>()
                .Where(c => c.Name.StartsWith("date_title"))
                .ToList();

            foreach (var col in columnsToRemove)
            {
                dataGridView1.Columns.Remove(col);
            }
            AddDateColumn("医生", "");
            // 5. 添加日期列
            foreach (var item in dateItems)
            {
                AddDateColumn(
                    item["date_title"]?.ToString(),
                    item["date"]?.ToString()
                );

                if (!keyValues.ContainsKey(item["date"]?.ToString()))
                {
                    keyValues[item["date"]?.ToString()] = item["date_title"]?.ToString();
                }
            }
        }
        private void InitDataGrid()
        {
            try
            {
                // 1. 获取日期参数（原逻辑不变）
                string BeginDateStr = "";
                string EndDateStr = "";
                if (DateTime.TryParse(BeginDate.Text, out DateTime beginDate))
                {
                    BeginDateStr = beginDate.ToString("yyyy-MM-dd");
                }
                if (DateTime.TryParse(EndDate.Text, out DateTime endDate))
                {
                    EndDateStr = endDate.ToString("yyyy-MM-dd");
                }
                var sign = TypecomboBox.SelectedItem == null ? "" : TypecomboBox.SelectedItem.ToString();
                // 2. 构造请求参数（原逻辑不变）

                var Request = new { end = EndDateStr, start = BeginDateStr, page = uiPagination1.ActivePage, limit = uiPagination1.PageSize.ToString(), sign = sign, keywords = Keywords.Text, client = "zm_hospital" };
                var result = BaseService.HttpService("api_back/api_scheduling/init_sch_records_internet_doc", Request);
                if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                {

                }
                else
                {
                    this.ShowErrorDialog(result.msg);
                    if (result.msg.Contains("认证失败")) { EventManager.Instance.RaiseStringEvent("登录界面"); }
                    return;
                }
                // 3. 反序列化数据（原逻辑不变）
                var data = JsonConvert.DeserializeObject<List<RecordModel>>(result?.data.ToString());

                // 4. 创建临时列表存储所有行数据
                List<Dictionary<string, object>> rowDataList = new List<Dictionary<string, object>>();

                if (data.Count > 0)
                {
                    foreach (var obj in data)
                    {
                        // 5. 为每行创建一个字典存储单元格值
                        Dictionary<string, object> rowData = new Dictionary<string, object>();

                        // 6. 填充固定列（如"医生"）
                        rowData["医生"] = obj.doc_name;
                        rowData["doc_id"] = obj.doc_id;

                        // 7. 动态处理其他字段
                        foreach (var item in GetNonEmptyFieldNames(obj))
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(item);
                            if (propertyInfo != null && item != "doc_id" && item != "doc_name" && keyValues.ContainsKey(item))
                            {
                                var fieldValue = propertyInfo.GetValue(obj);
                                string columnName = keyValues[item]; // 假设 keyValues 映射字段到列名
                                rowData[columnName] = fieldValue;
                            }
                        }

                        // 8. 将单行数据加入列表
                        rowDataList.Add(rowData);
                    }

                    // 9. 批量绑定数据到 DataGridView
                    BindDataToGrid(rowDataList);
                }
                var RCountequest = new { end = EndDateStr, start = BeginDateStr, page = 1, limit = 999999, sign = sign, keywords = Keywords.Text, client = "zm_hospital" };
                var rCesult = BaseService.HttpService("api_back/api_scheduling/init_sch_records_internet_doc", RCountequest);

                if (rCesult.status == "success" && null != rCesult.data && false == string.IsNullOrEmpty(rCesult.data.ToString()))
                {
                    var RCdata = JsonConvert.DeserializeObject<List<RecordModel>>(rCesult?.data.ToString());

                    uiPagination1.TotalCount = RCdata.Count;
                    uiLabel1.Text = $"总计:{uiPagination1.TotalCount.ToString()}条";
                }
            }
            catch (Exception) { }
        }

        // 10. 单独封装数据绑定方法
        private void BindDataToGrid(List<Dictionary<string, object>> rowDataList)
        {
            dataGridView1.Rows.Clear();

            // 动态创建列（如果列尚未初始化）
            if (dataGridView1.Columns.Count == 0)
            {
                dataGridView1.Columns.Add("医生", "医生");
                foreach (var columnName in keyValues.Values)
                {
                    dataGridView1.Columns.Add(columnName, columnName);
                }
            }

            // 批量添加行
            for (int i = 0; i < rowDataList.Count; i++)
            {
                var rowData = rowDataList[i];
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dataGridView1);

                // 按列顺序填充值
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    if (rowData.TryGetValue(column.HeaderText, out object value))
                    {
                        if (column.HeaderText == "医生")
                        {
                            row.Cells[column.Index].Value = rowData["医生"];

                        }
                        else
                        {
                            row.Cells[column.Index].Value = (value as kinds)?.kind_name_title;
                        }
                    }
                }

                // 设置Tag为原始对象
                if (i < rowDataList.Count)
                {
                    row.Tag = rowDataList[i];
                }

                dataGridView1.Rows.Add(row);
            }
        }
        static List<string> GetNonEmptyFieldNames(RecordModel data)
        {
            List<string> fieldNames = new List<string>();

            // Get all properties of the class
            var properties = typeof(RecordModel).GetProperties();

            // Iterate through each property
            foreach (var property in properties)
            {
                // Get the value of the property
                var value = property.GetValue(data);

                // If the value is not null, add the field name to the list
                if (value != null)
                {
                    fieldNames.Add(property.Name);
                }
            }

            return fieldNames;
        }
        private void AddDateColumn(string fieldName, string headerText)
        {
            // 创建带特殊样式的列
            var column = new DataGridViewTextBoxColumn
            {
                Name = fieldName,
                HeaderText = ValidateDateFormat(headerText),
                DataPropertyName = fieldName,
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Format = "yyyy-MM-dd",
                    Alignment = DataGridViewContentAlignment.MiddleCenter,
                    BackColor = Color.Lavender
                },
                HeaderCell = new DataGridViewColumnHeaderCell
                {
                    Style = new DataGridViewCellStyle
                    {
                        BackColor = Color.SteelBlue,
                        ForeColor = Color.White,
                        Font = new Font("Microsoft YaHei", 9F, FontStyle.Bold)
                    }
                }
                ,
                MinimumWidth = 130
            };

            dataGridView1.Columns.Add(column);
            // 启用全局自动列宽调整
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

        }
        private string ValidateDateFormat(string dateTitle)
        {
            // 验证日期格式并高亮错误
            var match = Regex.Match(dateTitle, @"（(\d{2}\.\d{2})）$");
            if (!match.Success)
            {
                //Logger.Warn($"非标准日期格式：{dateTitle}");
                return $"{dateTitle}⚠️"; // 添加错误标识
            }

            try
            {
                var dateStr = $"2023-{match.Groups[1].Value.Replace('.', '-')}";
                DateTime.Parse(dateStr);
                return dateTitle;
            }
            catch
            {
                //Logger.Error($"无效日期：{dateTitle}");
                return $"{dateTitle}❌"; // 添加错误标识
            }
        }

        private void QueryButton_Click_1(object sender, EventArgs e)
        {
            Init();
        }

        private void BeginDate_ValueChanged(object sender, DateTime value)
        {
            if (EndDate.Value < BeginDate.Value)
            {
                EndDate.Value = BeginDate.Value.AddMonths(1);
            }
            else if (EndDate.Value > BeginDate.Value.AddMonths(1))
            {
                EndDate.Value = BeginDate.Value.AddMonths(1);
            }
        }
        private void EndDate_ValueChanged(object sender, DateTime value)
        {
            DateTime maxEndDate = BeginDate.Value.AddMonths(1);
            if (EndDate.Value > maxEndDate)
            {
                EndDate.Value = maxEndDate;
            }
        }

        private async void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            Init();
        }
    }
}
